package com.moose.operator.exception;

import com.moose.operator.model.api.R;
import com.moose.operator.model.api.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * Description:
 * </p>
 *
 * @author taohua
 * @version v1.0.0
 * @date 2020-11-08 20:51:20:51
 * @see com.moose.operator.exception
 */

@Slf4j
@ControllerAdvice
public class MooseExceptionHandler {

  @ResponseBody
  @ExceptionHandler(Exception.class)
  public Object handleException(Exception e) {
    log.error("[自定义捕获全局异常] ", e);
    if (e instanceof BusinessException) {
      BusinessException exception = (BusinessException) e;
      Integer code = exception.getCode();
      String message = exception.getMessage();
      return R.fail(code, message);
    }
    if (e instanceof HttpMessageNotReadableException) {
      return R.fail(ResultCode.PARAMS_REQUEST_VALIDATE_FAIL);
    }
    return R.fail(ResultCode.UN_KNOWN_ERROR, e.getMessage());
  }
}
